
from __future__ import with_statement


import unittest
import Queue
import threading


class ThreadPipeEnd:
    def __init__(self, queue_rx, queue_tx):
        self.queue_rx = queue_rx
        self.queue_tx = queue_tx
        self._lock = threading.Lock()
    
    def send(self, data):
        with self._lock:
            self.queue_tx.put(data)
    
    def recv(self, timeout = None):
        data = None
        try:
            data = self.queue_rx.get(block = True, timeout = timeout)
        except Exception, e:
            pass
        return data


def ThreadPipe():
    a = Queue.Queue()
    b = Queue.Queue()
    pa = ThreadPipeEnd(a, b)
    pb = ThreadPipeEnd(b, a)
    return pa, pb


class TestSequenceFunctions(unittest.TestCase):
    def setUp(self):
        pass
    
    def testThreadPipe(self):
        a, b = ThreadPipe()
        self.assert_(not b.poll())
        a.send("hej")
        self.assert_(b.poll())
        self.assert_(b.recv() == "hej")
        self.assert_(not b.poll())


if __name__ == "__main__":
    unittest.main()
